BelongsTo   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 30
dl 0
loc 38
rs 10
c 0
b 0
f 0
wmc 7

2 Functions

Rating   Name   Duplication   Size   Complexity  
A setParentProperties 0 18 2
A setName 0 5 5
1
import Relation from "../Relation";
2
import {ModelStaticInterface} from "../../../JeloquentInterfaces";
3
4
export default class BelongsTo extends Relation {
5
6
    constructor(model: ModelStaticInterface, foreignKey: string|null = null, name: string = null) {
7
        super(model, (foreignKey ?? `${model.snakeCaseClassName}_id`), name);
8
    }
9
10
    get originalValue() {
11
        return this.model.find(this.$parent[`original_${this.foreignKey}`]);
12
    }
13
14
    get value() {
15
        return this.model.find(this.$parent[this.foreignKey]);
16
    }
17
18
    setName(): BelongsTo {
19
        const className = this.model.snakeCaseClassName;
20
        this.$name = this.$name ?? `${className}`;
21
        return this;
22
    }
23
24
    protected setParentProperties() {
25
        super.setParentProperties();
26
27
        let name = '';
28
        for (const namePart of this.$name.split('_')) {
29
            name += namePart[0].toUpperCase() + namePart.slice(1);
30
        }
31
        //TODO remove
32
        Object.defineProperty(this.$parent,
33
            `has${name}`, {
34
                get: () => {
35
                    return this.value !== null;
36
                },
37
            }
38
        )
39
40
        return this;
41
    }
42
}